//该文件无需在action中声明，会自动进行载入
define(['jquery','vue'],function(jquery,vue){
	setTimeout(function(){
		$('[name="tiaoMa"]').focus();
	},500);
    return {
        'tiaoMa:change' : function(data){
            var o = this.$attrs.row;
            var code = data;
            //定义一个空数组
            var arr = [];
		    var url = "?controller=Sample_SmChuku&action=GetKucun";
		    var multiUrl = "?controller=Sample_SmChuku&action=GetProduct";
            var params = {code:code,pagesize:20,currentPage:1};

            let _this = this;
            this.$http.post(url,params).then((res)=>{
				if(res.data.success){
					if(res.data.data.length > 1){
						if(!_this.compDialog) {
						    const Ctor  = vue.extend({
						      	template: `
							        <el-dialog
							        	width="80%"
							          	title="查看明细"
							          	:visible.sync="drawer"
							          	@open="handleOpen"
				      					height="30px"
							          	direction="rtl">
							          	<div :style="'width:100%;height:'+paramsData.bodyHeight+'px;'">
							        		<comp-table
										        :cols="columns"
										        :action="actionUrl"
										        ref="table"
										        height="290"
										        @row-dblclick="handleSelect"
										        >
										        <!-- 左上角插槽-搜索 -->
										        <template slot="leftTopSlot">
										          <!-- <div style="width:100%;"> -->
										            <!-- <el-input placeholder="关键字"  size="mini" v-model="key">
										              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
										            </el-input> -->
										            <div v-for="(item,index) in searchItems" :key="index" style="width:180px;float:left; margin-right:5px;margin-bottom:5px;">
										              <component
										                :is="item.type"
										                :fld="item"
										                :ref="item.name"
										                :value="searchConfig[item.name]"
										                :placeholder="item.title"
										                @input="searchConfig[item.name]=arguments[0]"
										              ></component>
										            </div>
										            <el-button icon="el-icon-search" circle size="mini" type="primary" @click="handleSearch"></el-button>

										          <!-- </div> -->
										        </template>

										        <!-- 左下角插槽-分页 -->
										        <template slot="leftBottomSlot">
										          <div style="float:left; margin-top:5px;" >
										            <div style="float:left;">
										              <el-pagination
										                @size-change="handleSizeChange"
										                @current-change="handleCurrentChange"
										                :current-page="currentPage"
										                :page-sizes="[20,50, 100, 200]"
										                :page-size="pagesize"
										                layout="prev, pager, next"
										                :total="total"
										                background
										              ></el-pagination>
										            </div>
										            <!-- 分页后的文字说明 -->
										            <!--<span style="float:left;margin-top:9px;" v-html="textAfterPage"></span> -->
										          </div>
										        </template>
									      	</comp-table>
									    </div>
							        </el-dialog>
						      	`,
						      	components: {
							        'comp-table' : resolve=>require(['_vue!pathComponent/comp-table'], resolve),
							        'comp-text' : resolve=>require(['_vue!pathComponent/comp-text'], resolve),
							        'comp-autocomplete' : resolve=>require(['_vue!pathComponent/comp-autocomplete'], resolve),
							        'comp-calendar' : resolve=>require(['_vue!pathComponent/comp-calendar'], resolve),
							        'comp-checkbox' : resolve=>require(['_vue!pathComponent/comp-checkbox'], resolve),
							        'comp-checkbox-group' : resolve=>require(['_vue!pathComponent/comp-checkbox-group'], resolve),
							        // 'comp-file' : resolve=>require(['_vue!pathComponent/comp-file'], resolve),
							        'comp-select' : resolve=>require(['_vue!pathComponent/comp-select'], resolve),
							        'comp-text-compose' : resolve=>require(['_vue!pathComponent/comp-text-compose'], resolve),
							        // 'comp-popup-select' : resolve=>require(['_vue!pathComponent/comp-popup-select'], resolve),
							    },
						    	// props:['fld','value','display-text'],
						        computed:{
							        
						      	},
						      	data: function () {
							        return {
							        	columns: {},
							          	drawer: false,
							          	actionUrl:multiUrl,
			          					searchItems : [],
				        				paramsData:{},
			          					params:{},
				        				currentPage:1,
							          	pagesize:20,
							          	total:400,//记录总数
			          					searchConfig : {},
			          					multiSelect:{},
			          					key:'',
			          					rowKey:'id',
							        }
						      	},
							    methods: {
							    	//设置displayText的值
							        //以下事件没用了,都是在handelselect事件中处理了
							        // handleModelInput :function(val){
							        //   this.$emit("input", val);
							        // },
							        //dialog打开前的回调
							        handleOpen :function(){
							          	//dom元素生成后,从服务器获取数据
							          	this.$nextTick(()=>{
							            	// this.$refs.table.multiSelect = this.multiSelect;
							            	this._getRows();
							          	});
							        },
							        //通过ajax请求从服务器获得数据
							        _getRows : function() {
							          	var url = this.actionUrl;
							          	if(url=='' || url==undefined) {
								            alert('popup-select 组件未定义action参数');
								            return false;
							          	}
							          	this.params.pagesize = this.pagesize;
							          	this.params.currentPage = this.currentPage;
							          	//将searchConfig中的值放入
								        for(var k in this.searchConfig) {
								            this.params[k] = this.searchConfig[k];
								        }
							          	this.$http.post(url, this.params)
							          	.then((response)=>{
							          		console.log({response});
								            var cols = this._formatColumns(response.data.columns);
								            var rows = this._formatRows(response.data.rows);
								            this.total = response.data.total;
								            this.$refs.table.columns = cols;
								            this.$refs.table.rows = rows;
							          	})
							          	.catch(function (error) {
							            	console.error(error);
							          	});
							        },
							        //格式化表头定义
							        _formatColumns : function(columns) {
							          	for(var key in columns) {
								            if(typeof(columns[key])=='string') {
								              	columns[key] = {'text':columns[key],'width':80};
								            }
							          	}
							          	return columns;
							        },
							        //格式化数据集
							        _formatRows : function(rows) {
							          	//判断返回的记录集中是否存在rowKey字段,
							          	//如果存在构造虚拟的rowKey,否则返回时有错.
							          	if(rows.length>0) {
								            if(rows[0][this.rowKey]==undefined) {
								              	console.warn(`后台返回的数据集中未包含${this.rowKey}字段,这可能导致确认回调时的错误!`);
								              	//构造虚拟的rowkey
								              	for(var i=0;rows[i];i++) {
								                	rows[i][this.rowKey] = i+1;
								              	}
								            }
							          	}
							          	return rows;
							        },
							        //页数改变时触发
							        handleSizeChange :function(size) {
							          	this.currentPage=1;
							          	this.pagesize=size;
							          	this._getRows();
							        },
							        handleCurrentChange : function(page) {
							          	this.currentPage=page;
							          	this._getRows();
							        },
							        //双击回调
							        handleSelect : function(row,e){
							          	// debugger;
							          	// console.log(row[key]);
							          	console.log(row);
							          	var sonRow = _this.$attrs.row.Products;
							          	for(var i = 0;i < sonRow.length;i++){
											if(row.code == sonRow[i].code && row.kuweiId == sonRow[i].kuweiId){
												this.$message('条码存在于第'+ (i+1)+'行,'+'请勿选择同一条入库记录','error');
												$('input[name="tiaoMa"]').val('');
												$('input[name="tiaoMa"]').focus();
												return false;
											}
										}
							          	this.drawer = false;
							          	_this.$root.row.Products.push(row);
							          	$('[name="tiaoMa"]').val('');
							          	$('[name="tiaoMa"]').focus();
							        },

							        //点击搜索
							        handleSearch : function() {
							          	this.currentPage=1;
							          	this._getRows();
							        },

							        //取消已选择结果
							        handleClear : function() {
							          	// this.text='';
							          	vue.set(this.$attrs.row,this.fld.displayKey,'');
							          	// this.$attrs.row[this.fld.displayKey] = '';
							          	// this.row[this.fld.displayKey] = '';
							          	// if(this.$attrs.row) {
							          	//   this.$attrs.row[this.fld.displayKey] = '';
							          	// }
							          	// this.$emit('clear',`${this.fld.name}:clear`,this);
							          	this.$emit('input','');
							        },

							        //根据配置信息,返回所有需要构造的搜索控件
							        //所有的搜索控件在Config/Searchitems_config.php中定义好了.
							        setSearchItems : function(opt) {
							          	var maxSearchItem = 5;
							          	var i=0;
							          	for(var k in opt) {
								            i++;
								            if(i>maxSearchItem) {
								              	delete(opt[k]);
								            }
							          	}
							          	if(i>maxSearchItem) {
							          	  	console.warn(`comp-popup-select控件(${this.fld.name})最多支持 ${maxSearchItem} 个搜索项`)
							          	}
							          	//确保opt只有3个
							          	this.searchConfig = opt;
							          	//从服务器获得高级搜索条目
							          	var url='?controller=searchitems&action=getcomps';
							          	//将this.searchitems转变成数组
							          	var temp=[]
							          	for(var key in opt) {
								            var _temp = typeof(opt[key])=="object"&&opt[key].hasOwnProperty('value') ? opt[key] : {value:opt[key]};
								            _temp.key = key;
								            temp.push(_temp);
							          	}
							          	var params={items:temp};
							          	// dump(params);
							          	this.$http.post(url,params).then((res)=>{
								            if(!res.data.success) {
								              	this.$notify.error({
									                'title':'保存失败',
									                'message':'response.data.success not found'
								              	});
								              	// dump(res);
								              	return false;
								            }
								            //开始处理返回的items
								            var items = res.data.items;
								            this.searchItems = items;
								            // dump(this.searchItems);

								            //根据服务器返回的字段定义,为this.params进行初始化
								            items.forEach((item,i)=>{
								              	//不能直接进行设置,因为params中的变量和控件存在绑定关系,简单创建变量不能生成绑定关系,必须使用Vue.set来进行设置
								              	// this.params[item.name]='';
								              	vue.set(this.params,item.name,opt[item.name]||'');
								            });

								            this.$emit('on-mount',this);

							          	}).catch(function (error) {
							            	console.error(error);
							            	this.$notify.error({
									            'title':'请求失败',
									            'message':'请求失败,检查url或者其他设置'
							           	 	});
							          	});
							        }
							    },
							    mounted() {
							    	this.setSearchItems({kuweiName:''});
							      	this.paramsData.bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
				      				this.paramsData.bodyHeight -= 150;
							      	console.log(document.documentElement.clientHeight);

				      				//处理弹框的url
							        this.actionUrl += "&code="+code;
							    },
						    });
						    let vm = new Ctor().$mount();
						    _this.compDialog = vm;
						    vm.drawer = true;
						    document.body.appendChild(vm.$el);
					  	}
		  				_this.compDialog.drawer =true;
					}else{
						for(var i = 0;i < this.$root.row.Products.length;i++){
							if(res.data.data[0].code == this.$root.row.Products[i].code && res.data.data[0].kuweiId == this.$root.row.Products[i].kuweiId){
								this.$message('条码存在于第'+ (i+1)+'行,'+'请勿重复扫码','error');
								$('input[name="tiaoMa"]').val('');
								$('input[name="tiaoMa"]').focus();
								return false;
							}
						}
						this.$root.row.Products.push(res.data.data[0]);
						// let lastPro = this.$root.row.Products.length-1;
						// vue.set(this.$root.row.Products[lastPro],'code',res.data.data[0].code);
						// vue.set(this.$root.row.Products[lastPro],'proName',res.data.data[0].proName);
						// vue.set(this.$root.row.Products[lastPro],'proDesc',res.data.data[0].proDesc);
						// vue.set(this.$root.row.Products[lastPro],'type',res.data.data[0].type);
						// vue.set(this.$root.row.Products[lastPro],'kuweiId',res.data.data[0].kuweiId);
						// vue.set(this.$root.row.Products[lastPro],'productId',res.data.data[0].productId);
						// vue.set(this.$root.row.Products[lastPro],'kuweiName',res.data.data[0].kuweiName);
						// vue.set(this.$root.row.Products[lastPro],'kucun',res.data.data[0].cnt);
						// console.log(this);
						$('input[name="tiaoMa"]').val('');
						$('input[name="tiaoMa"]').focus();
					}
				}else{
					this.$message(res.data.msg,'error');
					$('[name="tiaoMa"]').val('');
				}
				return;
            }).catch((error)=>{
				//服务器端返回success=false
				console.error(error);
            });
        },
    }
});